package main

import (
	"context"
	"flag"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"os"
	"yunzhan/alert-server/internal/logic"

	"yunzhan/alert-server/internal/config"
	"yunzhan/alert-server/internal/handler"
	"yunzhan/alert-server/internal/svc"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/rest"
)

var configFile = flag.String("f", "etc/config.yaml", "the config file")

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)
	logx.MustSetup(c.ServicesLogConfig["alertServer"].LogConf)

	logFilePath := fmt.Sprintf(`%s/alert-server.log`, c.ServicesLogConfig["alertServer"].LogConf.Path)
	file, err := os.OpenFile(logFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		logx.Error(err)
		return
	}
	defer file.Close()
	writer := logx.NewWriter(file)
	logx.SetWriter(writer)

	defer func() {
		err := logx.Close()
		if err != nil {
			panic(err)
		}
	}()
	// 创建 REST 服务器
	serviceConfig, ok := c.RestServices["alertServer"]
	if !ok {
		logx.Errorf("Service %s not found in config file", "alert-server")
	}

	server := rest.MustNewServer(serviceConfig.RestConf)
	defer server.Stop()

	// 创建服务上下文
	ctx := svc.NewServiceContext(c)

	// 注册处理器
	handler.RegisterHandlers(server, ctx)

	// 启动告警监控服务
	logic.StartAlertMonitoring(context.Background(), ctx)

	logx.Infof("Starting %s at %s:%d...", serviceConfig.RestConf.Name, serviceConfig.RestConf.Host, serviceConfig.RestConf.Port)

	// 启动服务器
	server.Start()
}
